import {Component, OnInit} from '@angular/core';
import {Router, ActivatedRoute} from "@angular/router";
import {Question} from "../../question";
import {TrainingService} from "../../my-service/training.service";
import {UtilService} from "../../my-service/util.service";

@Component({
  selector: 'app-answer',
  templateUrl: './answer.component.html',
  styleUrls: ['./answer.component.css'],
})
export class AnswerComponent implements OnInit {
  trainingID: string;//训练的ID
  userGuid: string;//用户的Guid
  answerCardID: string;//答题卡ID
  questions: any;
  currentQuestionIndex = 0;//还没有做的题的最近索引
  score = {
    adventureScore: 0, //冒险型成绩
    curiosityScore: 0, //好奇型成绩
    imaginationScore: 0,//想象力成绩
    challengeScore: 0, //挑战性成绩
  }; //威廉斯量表测试成绩由四部分组成
  Content = [];//答题卡content
  adventureNums = [1, 5, 21, 24, 25, 28, 36, 43, 44, 29, 35];//冒险性对应的题号
  curiosityNums = [2, 8, 11, 19, 27, 32, 34, 37, 38, 39, 47, 49, 12, 48];//好奇型对应的题号
  imaginationNums = [6, 13, 14, 16, 20, 22, 23, 30, 31, 40, 32, 36, 45];//想象型对应的题号
  challengeNums = [3, 7, 10, 15, 18, 26, 41, 42, 50, 4, 9, 17];//挑战型对应的题号
  positionBase = 50; //偏移基础值
  answerCoverIndex = 0;

  constructor(private trainingService: TrainingService,
              private router: Router,
              private routerInfo: ActivatedRoute,
              private utilService: UtilService,) {
    this.questions = [];
  }

  /*获取试卷题目*/
  getQuestions() {
    this.trainingService.getQuestionByPaperId().then(res => {
      if (res.status == 1) {
        res.data.forEach(val => {
          let question = new Question(val.PK_QuestionGuid, val.Index, val.Content, val.Status);
          let arr = val.Option.substring(1, val.Option.length - 1); //去除首尾的双引号
          let options = JSON.parse(arr);
          let i = 0;
          let num;
          options.forEach(o => {
            if (i == 0) num = 'A:';
            else if (i == 1) num = 'B:';
            else num = 'C:';
            question.addOption(o.content, o.score, num);
            i++;
          });
          this.questions.push(question);
        });
      }
    })
  }

  /*获取答题卡，如果用户没有答题卡就去创建一个答题卡*/
  getAnswerCard(trainingID, userID) {
    this.trainingService.getCard(trainingID, userID).then(res => {
      if (res.status == 1) {
        if (res.data[0]) {
          //有答题卡
          this.answerCardID = res.data[0].PK_AnwserCardGuid;
          if (res.data[0].Content) {
            this.Content = JSON.parse(res.data[0].Content);
            this.currentQuestionIndex = this.Content[this.Content.length - 1].selectedOptionIndex + 1;
            if (this.currentQuestionIndex == 50) {
              //已经答完题了直接到查看结果的页面
              this.router.navigate(['../result', {
                cardID: this.answerCardID,
                id: this.trainingID
              }], {relativeTo: this.routerInfo});
            }
          }
          if (res.data[0].Score) {
            this.score = JSON.parse(res.data[0].Score);
          }
        } else {
          //没有答题卡，创建答题卡
          this.trainingService.createCard(trainingID, userID).then(res => {
            if (res.status == 1) {
              this.answerCardID = res.data;
            }
          });
        }
      }
    })
  }

  /*更新答题卡*/
  updateAnwserCard(content, score) {
    this.trainingService.updateCardByID(this.answerCardID, content, score).then(res => {
      if (res.status == 1) {
        this.currentQuestionIndex += 1;
        if (this.currentQuestionIndex == 50) {
          this.updateFinish();
          this.router.navigate(['../result', {
            cardID: this.answerCardID,
            id: this.trainingID
          }], {relativeTo: this.routerInfo});
        }
      }
    })
  }

  /*更新答题卡完成状态*/
  updateFinish() {
    this.trainingService.updateFinishById(this.answerCardID).then(res => {
      if (res.status == 1) {
      }
    })
  }

  ngOnInit() {
    this.trainingID = this.routerInfo.snapshot.params.ID;
    this.answerCardID = this.routerInfo.snapshot.params.answerID;
    if (!this.answerCardID) {
      //非匿名测试
      this.utilService.getUserInfo().then(res => {
        if (res.status == 1) {
          this.userGuid = res.userGuid;
          this.getAnswerCard(this.trainingID, this.userGuid);
        }
      });
    }
    this.getQuestions();
  }

//  选择答案
  selectAnwser(question, index, questionNum) {
    if (this.currentQuestionIndex <= 49) {
      //进行背景图片的切换
      this.answerCoverIndex++;
      if (this.answerCoverIndex > 2) {
        this.answerCoverIndex = 0;
      }
      //答题卡的书写
      let grade = question.options[index].grade;
      let cardContent = {questionGuid: question.id, selectedOptionIndex: this.currentQuestionIndex};
      this.Content[this.currentQuestionIndex] = cardContent;
      //判断当前题目是属于哪种类型的
      if (this.adventureNums.indexOf(questionNum) !== -1) this.score.adventureScore += grade;
      else if (this.curiosityNums.indexOf(questionNum) !== -1) this.score.curiosityScore += grade;
      else if (this.imaginationNums.indexOf(questionNum) !== -1) this.score.imaginationScore += grade;
      else this.score.challengeScore += grade;
    }
    this.updateAnwserCard(this.Content, this.score);
  }

}
